﻿using System;
using System.Text;
using RAP.Framework.Libary.ServerCacheManager;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Cache;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.Cache
{
	/// <summary>
	/// 设置指定键的缓存
	/// </summary>
	public class SetCacheHandler : CacheHandlerBase
    {
        public new SetCache Element
        {
            get
            {
                return base.Element as SetCache;
            }
            set
            {
                base.Element = value;
            }
        }

        public override void DoRender( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
        {
			var fullKey = this.GetFieldName( rootParamObject, parentParamObject, context );
            if ( fullKey.IsNullOrEmpty( ) )
            {
                throw new NullReferenceException( "缓存的key不能为空！" );
            }
			var sbValue = new StringBuilder( );
            this.Element.CacheValue.Handler.DoRender( sbValue, rootParamObject, parentParamObject, context );
			var fieldName = sbValue.ToString( ).Trim( );
			var paramObject = this.GetParamObject( rootParamObject, parentParamObject, context );
			var value = ExpressionUtils.GetFieldValue
            (
                fieldName
                , rootParamObject
                , parentParamObject
                , context
                , ( ) => paramObject.GetValue( fieldName ).IsNullValue( ( ) => this.GetConvertedValue( fieldName ) )
            );
            CacheManager.Instance.Set( fullKey, value );
        }
    }
}
